package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.pojo.Device;
import com.zhentao.pojo.DeviceMaintenance;
import com.zhentao.pojo.DeviceOperation;
import com.zhentao.service.DeviceMaintenanceService;
import com.zhentao.service.DeviceOperationService;
import com.zhentao.service.DeviceService;
import com.zhentao.util.Result;
import com.zhentao.vo.DeviceMaintenanceVO;
import com.zhentao.vo.DeviceOperationVO;
import com.zhentao.vo.DeviceQueryVO;
import com.zhentao.vo.DeviceVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 设备管理Controller
 * @date: 2025/8/14 8:58
 * @author: ftt
 */
@RestController
@RequestMapping("/device")
@CrossOrigin
public class DeviceController {

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private DeviceMaintenanceService deviceMaintenanceService;

    @Autowired
    private DeviceOperationService deviceOperationService;

    /**
     * 测试接口
     */
    @GetMapping("/test")
    public Result<String> test() {
        return Result.success("设备管理服务正常运行");
    }

    // ==================== 设备档案管理 ====================

    /**
     * 分页查询设备列表
     */
    @PostMapping("/page")
    public Result<IPage<DeviceVO>> getDevicePage(@RequestBody DeviceQueryVO queryVO) {
        try {
            Page<Device> page = new Page<>(queryVO.getCurrent(), queryVO.getSize());
            QueryWrapper<Device> queryWrapper = new QueryWrapper<>();
            
            if (queryVO.getDeviceNo() != null && !queryVO.getDeviceNo().trim().isEmpty()) {
                queryWrapper.like("device_no", queryVO.getDeviceNo());
            }
            if (queryVO.getDeviceName() != null && !queryVO.getDeviceName().trim().isEmpty()) {
                queryWrapper.like("device_name", queryVO.getDeviceName());
            }
            if (queryVO.getDeviceType() != null && !queryVO.getDeviceType().trim().isEmpty()) {
                queryWrapper.eq("device_type", queryVO.getDeviceType());
            }
            if (queryVO.getStatus() != null) {
                queryWrapper.eq("status", queryVO.getStatus());
            }
            
            // queryWrapper.orderByDesc("create_time");
            
            IPage<Device> devicePage = deviceService.page(page, queryWrapper);
            
            // 转换为VO
            IPage<DeviceVO> voPage = new Page<>(devicePage.getCurrent(), devicePage.getSize(), devicePage.getTotal());
            List<DeviceVO> voList = new ArrayList<>();
            for (Device device : devicePage.getRecords()) {
                voList.add(convertToVO(device));
            }
            voPage.setRecords(voList);
            
            return Result.success(voPage);
        } catch (Exception e) {
            return Result.error("查询设备列表失败：" + e.getMessage());
        }
    }

    /**
     * 根据ID查询设备详情
     */
    @GetMapping("/{id}")
    public Result<DeviceVO> getDeviceById(@PathVariable Long id) {
        try {
            Device device = deviceService.getById(id);
            if (device == null) {
                return Result.error("设备不存在");
            }
            
            return Result.success(convertToVO(device));
        } catch (Exception e) {
            return Result.error("查询设备详情失败：" + e.getMessage());
        }
    }

    /**
     * 新增设备
     */
    @PostMapping
    public Result<String> addDevice(@RequestBody DeviceVO deviceVO) {
        try {
            // 数据验证
            if (deviceVO.getDeviceName() == null || deviceVO.getDeviceName().trim().isEmpty()) {
                return Result.error("设备名称不能为空");
            }
            if (deviceVO.getDeviceType() == null || deviceVO.getDeviceType().trim().isEmpty()) {
                return Result.error("设备类型不能为空");
            }
            
            // 生成设备编号
            deviceVO.setDeviceNo(generateDeviceNo());
            deviceVO.setStatus(0); // 默认闲置状态
            deviceVO.setCreateTime(new Date());
            deviceVO.setUpdateTime(new Date());
            
            // 保存设备
            boolean saved = deviceService.save(deviceVO);
            if (!saved) {
                return Result.error("保存设备失败");
            }
            
            return Result.success("设备创建成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("创建设备失败：" + e.getMessage());
        }
    }

    /**
     * 更新设备
     */
    @PutMapping("/{id}")
    public Result<String> updateDevice(@PathVariable Long id, @RequestBody DeviceVO deviceVO) {
        try {
            Device existingDevice = deviceService.getById(id);
            if (existingDevice == null) {
                return Result.error("设备不存在");
            }
            
            deviceVO.setId(id);
            deviceVO.setUpdateTime(new Date());
            
            // 更新设备
            boolean updated = deviceService.updateById(deviceVO);
            if (!updated) {
                return Result.error("更新设备失败");
            }
            
            return Result.success("设备更新成功");
        } catch (Exception e) {
            return Result.error("更新设备失败：" + e.getMessage());
        }
    }

    /**
     * 删除设备
     */
    @DeleteMapping("/{id}")
    public Result<String> deleteDevice(@PathVariable Long id) {
        try {
            Device device = deviceService.getById(id);
            if (device == null) {
                return Result.error("设备不存在");
            }
            
            // 检查设备是否在使用中
            if (device.getStatus() == 1) {
                return Result.error("设备正在使用中，无法删除");
            }
            
            boolean removed = deviceService.removeById(id);
            if (!removed) {
                return Result.error("删除设备失败");
            }
            
            return Result.success("设备删除成功");
        } catch (Exception e) {
            return Result.error("删除设备失败：" + e.getMessage());
        }
    }

    /**
     * 获取设备状态列表
     */
    @GetMapping("/status/list")
    public Result<List<Map<String, Object>>> getDeviceStatusList() {
        try {
            List<Map<String, Object>> statusList = new ArrayList<>();
            Map<String, Object> status0 = new HashMap<>();
            status0.put("value", 0);
            status0.put("label", "闲置");
            statusList.add(status0);
            
            Map<String, Object> status1 = new HashMap<>();
            status1.put("value", 1);
            status1.put("label", "使用中");
            statusList.add(status1);
            
            Map<String, Object> status2 = new HashMap<>();
            status2.put("value", 2);
            status2.put("label", "维修中");
            statusList.add(status2);
            
            Map<String, Object> status3 = new HashMap<>();
            status3.put("value", 3);
            status3.put("label", "报废");
            statusList.add(status3);
            
            return Result.success(statusList);
        } catch (Exception e) {
            return Result.error("获取状态列表失败：" + e.getMessage());
        }
    }

    /**
     * 获取设备类型列表
     */
    @GetMapping("/type/list")
    public Result<List<Map<String, Object>>> getDeviceTypeList() {
        try {
            List<Map<String, Object>> typeList = new ArrayList<>();
            Map<String, Object> type1 = new HashMap<>();
            type1.put("value", "PRODUCTION");
            type1.put("label", "生产设备");
            typeList.add(type1);
            
            Map<String, Object> type2 = new HashMap<>();
            type2.put("value", "TESTING");
            type2.put("label", "检测设备");
            typeList.add(type2);
            
            Map<String, Object> type3 = new HashMap<>();
            type3.put("value", "TRANSPORT");
            type3.put("label", "运输设备");
            typeList.add(type3);
            
            Map<String, Object> type4 = new HashMap<>();
            type4.put("value", "OFFICE");
            type4.put("label", "办公设备");
            typeList.add(type4);
            
            return Result.success(typeList);
        } catch (Exception e) {
            return Result.error("获取类型列表失败：" + e.getMessage());
        }
    }

    // ==================== 设备维护管理 ====================

    /**
     * 分页查询设备维护列表
     */
    @PostMapping("/maintenance/page")
    public Result<IPage<DeviceMaintenanceVO>> getDeviceMaintenancePage(@RequestBody Map<String, Object> params) {
        try {
            System.out.println("=== 设备维护查询开始 ===");
            System.out.println("查询参数: " + params);
            
            QueryWrapper<DeviceMaintenance> wrapper = new QueryWrapper<>();
            
            // 维护单号模糊查询
            if (params.get("maintenanceNo") != null && !params.get("maintenanceNo").toString().trim().isEmpty()) {
                wrapper.like("maintenance_no", params.get("maintenanceNo").toString().trim());
            }
            
            // 维护类型查询
            if (params.get("maintenanceType") != null && !params.get("maintenanceType").toString().trim().isEmpty()) {
                wrapper.eq("maintenance_type", params.get("maintenanceType"));
            }
            
            // 维护状态查询
            if (params.get("status") != null && !params.get("status").toString().trim().isEmpty()) {
                wrapper.eq("status", params.get("status"));
            }
            
            // 设备ID查询
            if (params.get("deviceId") != null) {
                wrapper.eq("device_id", params.get("deviceId"));
            }
            
            // 按创建时间倒序
            // wrapper.orderByDesc("create_time");
            
            System.out.println("查询条件: " + wrapper.getSqlSegment());
            
            // 分页查询
            Integer current = (Integer) params.get("current");
            Integer size = (Integer) params.get("size");
            if (current == null) current = 1;
            if (size == null) size = 10;
            
            System.out.println("分页参数 - current: " + current + ", size: " + size);
            
            Page<DeviceMaintenance> page = new Page<>(current, size);
            IPage<DeviceMaintenance> maintenancePage = deviceMaintenanceService.page(page, wrapper);
            
            // 添加调试日志
            System.out.println("设备维护查询结果 - 总数: " + maintenancePage.getTotal());
            System.out.println("设备维护查询结果 - 记录数: " + maintenancePage.getRecords().size());
            
            // 转换为VO
            IPage<DeviceMaintenanceVO> voPage = new Page<>(current, size);
            voPage.setTotal(maintenancePage.getTotal());
            voPage.setPages(maintenancePage.getPages());
            
            List<DeviceMaintenanceVO> voList = new ArrayList<>();
            for (DeviceMaintenance maintenance : maintenancePage.getRecords()) {
                voList.add(convertMaintenanceToVO(maintenance));
            }
            voPage.setRecords(voList);
            
            System.out.println("=== 设备维护查询结束 ===");
            return Result.success(voPage);
        } catch (Exception e) {
            System.out.println("设备维护查询异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error("查询设备维护列表失败：" + e.getMessage());
        }
    }

    /**
     * 根据ID查询设备维护详情
     */
    @GetMapping("/maintenance/{id}")
    public Result<DeviceMaintenanceVO> getDeviceMaintenanceById(@PathVariable Long id) {
        try {
            DeviceMaintenance maintenance = deviceMaintenanceService.getById(id);
            if (maintenance == null) {
                return Result.error("维护记录不存在");
            }
            
            return Result.success(convertMaintenanceToVO(maintenance));
        } catch (Exception e) {
            return Result.error("查询维护详情失败：" + e.getMessage());
        }
    }

    /**
     * 新增设备维护
     */
    @PostMapping("/maintenance")
    public Result<String> addDeviceMaintenance(@RequestBody DeviceMaintenanceVO maintenanceVO) {
        try {
            // 数据验证
            if (maintenanceVO.getDeviceId() == null) {
                return Result.error("设备ID不能为空");
            }
            if (maintenanceVO.getMaintenanceType() == null) {
                return Result.error("维护类型不能为空");
            }
            
            // 生成维护单号
            maintenanceVO.setMaintenanceNo(generateMaintenanceNo());
            maintenanceVO.setStatus(0); // 待维护状态
            maintenanceVO.setCreateTime(new Date());
            maintenanceVO.setUpdateTime(new Date());
            
            // 保存维护记录
            boolean saved = deviceMaintenanceService.save(maintenanceVO);
            if (!saved) {
                return Result.error("保存维护记录失败");
            }
            
            return Result.success("维护记录创建成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("创建维护记录失败：" + e.getMessage());
        }
    }

    /**
     * 更新设备维护
     */
    @PutMapping("/maintenance/{id}")
    public Result<String> updateDeviceMaintenance(@PathVariable Long id, @RequestBody DeviceMaintenanceVO maintenanceVO) {
        try {
            DeviceMaintenance existingMaintenance = deviceMaintenanceService.getById(id);
            if (existingMaintenance == null) {
                return Result.error("维护记录不存在");
            }
            
            maintenanceVO.setId(id);
            maintenanceVO.setUpdateTime(new Date());
            
            // 更新维护记录
            boolean updated = deviceMaintenanceService.updateById(maintenanceVO);
            if (!updated) {
                return Result.error("更新维护记录失败");
            }
            
            return Result.success("维护记录更新成功");
        } catch (Exception e) {
            return Result.error("更新维护记录失败：" + e.getMessage());
        }
    }

    /**
     * 删除设备维护
     */
    @DeleteMapping("/maintenance/{id}")
    public Result<String> deleteDeviceMaintenance(@PathVariable Long id) {
        try {
            DeviceMaintenance maintenance = deviceMaintenanceService.getById(id);
            if (maintenance == null) {
                return Result.error("维护记录不存在");
            }
            
            // 检查维护状态
            if (maintenance.getStatus() == 1) {
                return Result.error("维护正在进行中，无法删除");
            }
            
            boolean removed = deviceMaintenanceService.removeById(id);
            if (!removed) {
                return Result.error("删除维护记录失败");
            }
            
            return Result.success("维护记录删除成功");
        } catch (Exception e) {
            return Result.error("删除维护记录失败：" + e.getMessage());
        }
    }

    /**
     * 开始维护
     */
    @PostMapping("/maintenance/{id}/start")
    public Result<String> startMaintenance(@PathVariable Long id) {
        try {
            DeviceMaintenance maintenance = deviceMaintenanceService.getById(id);
            if (maintenance == null) {
                return Result.error("维护记录不存在");
            }
            
            if (maintenance.getStatus() != 0) {
                return Result.error("只有待维护状态的记录可以开始维护");
            }
            
            maintenance.setStatus(1); // 维护中状态
            maintenance.setActualStartTime(new Date());
            maintenance.setUpdateTime(new Date());
            
            boolean updated = deviceMaintenanceService.updateById(maintenance);
            if (!updated) {
                return Result.error("开始维护失败");
            }
            
            return Result.success("维护已开始");
        } catch (Exception e) {
            return Result.error("开始维护失败：" + e.getMessage());
        }
    }

    /**
     * 完成维护
     */
    @PostMapping("/maintenance/{id}/complete")
    public Result<String> completeMaintenance(@PathVariable Long id, @RequestBody Map<String, Object> params) {
        try {
            DeviceMaintenance maintenance = deviceMaintenanceService.getById(id);
            if (maintenance == null) {
                return Result.error("维护记录不存在");
            }
            
            if (maintenance.getStatus() != 1) {
                return Result.error("只有维护中状态的记录可以完成");
            }
            
            maintenance.setStatus(2); // 已完成状态
            maintenance.setActualEndTime(new Date());
            maintenance.setMaintenanceResult((String) params.get("maintenanceResult"));
            
            // 安全地转换维护费用
            Object costObj = params.get("maintenanceCost");
            if (costObj != null) {
                if (costObj instanceof BigDecimal) {
                    maintenance.setMaintenanceCost((BigDecimal) costObj);
                } else if (costObj instanceof Integer) {
                    maintenance.setMaintenanceCost(new BigDecimal((Integer) costObj));
                } else if (costObj instanceof String) {
                    try {
                        maintenance.setMaintenanceCost(new BigDecimal((String) costObj));
                    } catch (NumberFormatException e) {
                        maintenance.setMaintenanceCost(BigDecimal.ZERO);
                    }
                } else {
                    maintenance.setMaintenanceCost(BigDecimal.ZERO);
                }
            } else {
                maintenance.setMaintenanceCost(BigDecimal.ZERO);
            }
            maintenance.setUpdateTime(new Date());
            
            boolean updated = deviceMaintenanceService.updateById(maintenance);
            if (!updated) {
                return Result.error("完成维护失败");
            }
            
            return Result.success("维护已完成");
        } catch (Exception e) {
            return Result.error("完成维护失败：" + e.getMessage());
        }
    }

    // ==================== 设备运行管理 ====================

    /**
     * 分页查询设备运行记录
     */
    @PostMapping("/operation/page")
    public Result<IPage<DeviceOperationVO>> getDeviceOperationPage(@RequestBody Map<String, Object> params) {
        try {
            System.out.println("=== 设备运行查询开始 ===");
            System.out.println("查询参数: " + params);
            
            QueryWrapper<DeviceOperation> wrapper = new QueryWrapper<>();
            
            // 运行记录编号模糊查询
            if (params.get("operationNo") != null && !params.get("operationNo").toString().trim().isEmpty()) {
                wrapper.like("operation_no", params.get("operationNo").toString().trim());
            }
            
            // 运行状态查询
            if (params.get("operationStatus") != null && !params.get("operationStatus").toString().trim().isEmpty()) {
                wrapper.eq("operation_status", params.get("operationStatus"));
            }
            
            // 设备ID查询
            if (params.get("deviceId") != null) {
                wrapper.eq("device_id", params.get("deviceId"));
            }
            
            // 按创建时间倒序
            // wrapper.orderByDesc("create_time");
            
            System.out.println("查询条件: " + wrapper.getSqlSegment());
            
            // 分页查询
            Integer current = (Integer) params.get("current");
            Integer size = (Integer) params.get("size");
            if (current == null) current = 1;
            if (size == null) size = 10;
            
            System.out.println("分页参数 - current: " + current + ", size: " + size);
            
            Page<DeviceOperation> page = new Page<>(current, size);
            IPage<DeviceOperation> operationPage = deviceOperationService.page(page, wrapper);
            
            // 添加调试日志
            System.out.println("设备运行查询结果 - 总数: " + operationPage.getTotal());
            System.out.println("设备运行查询结果 - 记录数: " + operationPage.getRecords().size());
            
            // 转换为VO
            IPage<DeviceOperationVO> voPage = new Page<>(current, size);
            voPage.setTotal(operationPage.getTotal());
            voPage.setPages(operationPage.getPages());
            
            List<DeviceOperationVO> voList = new ArrayList<>();
            for (DeviceOperation operation : operationPage.getRecords()) {
                voList.add(convertOperationToVO(operation));
            }
            voPage.setRecords(voList);
            
            System.out.println("=== 设备运行查询结束 ===");
            return Result.success(voPage);
        } catch (Exception e) {
            System.out.println("设备运行查询异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error("查询设备运行记录失败：" + e.getMessage());
        }
    }

    /**
     * 根据ID查询设备运行记录详情
     */
    @GetMapping("/operation/{id}")
    public Result<DeviceOperationVO> getDeviceOperationById(@PathVariable Long id) {
        try {
            DeviceOperation operation = deviceOperationService.getById(id);
            if (operation == null) {
                return Result.error("运行记录不存在");
            }
            
            return Result.success(convertOperationToVO(operation));
        } catch (Exception e) {
            return Result.error("查询运行记录详情失败：" + e.getMessage());
        }
    }

    /**
     * 新增设备运行记录
     */
    @PostMapping("/operation")
    public Result<String> addDeviceOperation(@RequestBody DeviceOperationVO operationVO) {
        try {
            // 数据验证
            if (operationVO.getDeviceId() == null) {
                return Result.error("设备ID不能为空");
            }
            if (operationVO.getOperationStatus() == null) {
                return Result.error("运行状态不能为空");
            }
            if (operationVO.getStartTime() == null) {
                return Result.error("开始时间不能为空");
            }
            
            // 生成运行记录编号
            operationVO.setOperationNo(generateOperationNo());
            operationVO.setCreateTime(new Date());
            operationVO.setUpdateTime(new Date());
            
            // 保存运行记录
            boolean saved = deviceOperationService.save(operationVO);
            if (!saved) {
                return Result.error("保存运行记录失败");
            }
            
            return Result.success("运行记录创建成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("创建运行记录失败：" + e.getMessage());
        }
    }

    /**
     * 更新设备运行记录
     */
    @PutMapping("/operation/{id}")
    public Result<String> updateDeviceOperation(@PathVariable Long id, @RequestBody DeviceOperationVO operationVO) {
        try {
            DeviceOperation existingOperation = deviceOperationService.getById(id);
            if (existingOperation == null) {
                return Result.error("运行记录不存在");
            }
            
            operationVO.setId(id);
            operationVO.setUpdateTime(new Date());
            
            // 更新运行记录
            boolean updated = deviceOperationService.updateById(operationVO);
            if (!updated) {
                return Result.error("更新运行记录失败");
            }
            
            return Result.success("运行记录更新成功");
        } catch (Exception e) {
            return Result.error("更新运行记录失败：" + e.getMessage());
        }
    }

    /**
     * 删除设备运行记录
     */
    @DeleteMapping("/operation/{id}")
    public Result<String> deleteDeviceOperation(@PathVariable Long id) {
        try {
            DeviceOperation operation = deviceOperationService.getById(id);
            if (operation == null) {
                return Result.error("运行记录不存在");
            }
            
            boolean removed = deviceOperationService.removeById(id);
            if (!removed) {
                return Result.error("删除运行记录失败");
            }
            
            return Result.success("运行记录删除成功");
        } catch (Exception e) {
            return Result.error("删除运行记录失败：" + e.getMessage());
        }
    }

    /**
     * 结束运行
     */
    @PostMapping("/operation/{id}/end")
    public Result<String> endOperation(@PathVariable Long id, @RequestBody Map<String, Object> params) {
        try {
            DeviceOperation operation = deviceOperationService.getById(id);
            if (operation == null) {
                return Result.error("运行记录不存在");
            }
            
            if (operation.getEndTime() != null) {
                return Result.error("运行记录已结束");
            }
            
            operation.setEndTime(new Date());
            operation.setRunHours((java.math.BigDecimal) params.get("runHours"));
            operation.setEfficiency((java.math.BigDecimal) params.get("efficiency"));
            operation.setEnergyConsumption((java.math.BigDecimal) params.get("energyConsumption"));
            operation.setOutput((java.math.BigDecimal) params.get("output"));
            operation.setUpdateTime(new Date());
            
            boolean updated = deviceOperationService.updateById(operation);
            if (!updated) {
                return Result.error("结束运行失败");
            }
            
            return Result.success("运行已结束");
        } catch (Exception e) {
            return Result.error("结束运行失败：" + e.getMessage());
        }
    }

    // ==================== 工具方法 ====================

    /**
     * 转换为设备VO
     */
    private DeviceVO convertToVO(Device device) {
        DeviceVO vo = new DeviceVO();
        // 复制基本属性
        vo.setId(device.getId());
        vo.setDeviceNo(device.getDeviceNo());
        vo.setDeviceName(device.getDeviceName());
        vo.setDeviceType(device.getDeviceType());
        vo.setDeviceModel(device.getDeviceModel());
        vo.setDeviceSpec(device.getDeviceSpec());
        vo.setManufacturer(device.getManufacturer());
        vo.setSupplier(device.getSupplier());
        vo.setPurchaseDate(device.getPurchaseDate());
        vo.setPurchasePrice(device.getPurchasePrice());
        vo.setStatus(device.getStatus());
        vo.setLocation(device.getLocation());
        vo.setResponsiblePerson(device.getResponsiblePerson());
        vo.setContactPhone(device.getContactPhone());
        vo.setDescription(device.getDescription());
        vo.setRemark(device.getRemark());
        vo.setTenantId(device.getTenantId());
        vo.setCreateUser(device.getCreateUser());
        vo.setCreateTime(device.getCreateTime());
        vo.setUpdateTime(device.getUpdateTime());
        
        // 设置状态名称
        switch (device.getStatus()) {
            case 0:
                vo.setStatusName("闲置");
                break;
            case 1:
                vo.setStatusName("使用中");
                break;
            case 2:
                vo.setStatusName("维修中");
                break;
            case 3:
                vo.setStatusName("报废");
                break;
            default:
                vo.setStatusName("未知");
                break;
        }
        
        // 设置设备类型名称
        switch (device.getDeviceType()) {
            case "PRODUCTION":
                vo.setDeviceTypeName("生产设备");
                break;
            case "TESTING":
                vo.setDeviceTypeName("检测设备");
                break;
            case "TRANSPORT":
                vo.setDeviceTypeName("运输设备");
                break;
            case "OFFICE":
                vo.setDeviceTypeName("办公设备");
                break;
            default:
                vo.setDeviceTypeName("未知");
                break;
        }
        
        return vo;
    }

    /**
     * 转换为维护VO
     */
    private DeviceMaintenanceVO convertMaintenanceToVO(DeviceMaintenance maintenance) {
        DeviceMaintenanceVO vo = new DeviceMaintenanceVO();
        // 复制基本属性
        vo.setId(maintenance.getId());
        vo.setMaintenanceNo(maintenance.getMaintenanceNo());
        vo.setDeviceId(maintenance.getDeviceId());
        vo.setMaintenanceType(maintenance.getMaintenanceType());
        vo.setStatus(maintenance.getStatus());
        vo.setPlanStartTime(maintenance.getPlanStartTime());
        vo.setPlanEndTime(maintenance.getPlanEndTime());
        vo.setActualStartTime(maintenance.getActualStartTime());
        vo.setActualEndTime(maintenance.getActualEndTime());
        vo.setMaintainer(maintenance.getMaintainer());
        vo.setMaintenanceCost(maintenance.getMaintenanceCost());
        vo.setMaintenanceContent(maintenance.getMaintenanceContent());
        vo.setMaintenanceResult(maintenance.getMaintenanceResult());
        vo.setFaultDescription(maintenance.getFaultDescription());
        vo.setSolution(maintenance.getSolution());
        vo.setRemark(maintenance.getRemark());
        vo.setTenantId(maintenance.getTenantId());
        vo.setCreateUser(maintenance.getCreateUser());
        vo.setCreateTime(maintenance.getCreateTime());
        vo.setUpdateTime(maintenance.getUpdateTime());
        
        // 设置维护状态名称
        switch (maintenance.getStatus()) {
            case 0:
                vo.setStatusName("待维护");
                break;
            case 1:
                vo.setStatusName("维护中");
                break;
            case 2:
                vo.setStatusName("已完成");
                break;
            case 3:
                vo.setStatusName("已取消");
                break;
            default:
                vo.setStatusName("未知");
                break;
        }
        
        // 设置维护类型名称
        switch (maintenance.getMaintenanceType()) {
            case 1:
                vo.setMaintenanceTypeName("日常保养");
                break;
            case 2:
                vo.setMaintenanceTypeName("定期维护");
                break;
            case 3:
                vo.setMaintenanceTypeName("故障维修");
                break;
            case 4:
                vo.setMaintenanceTypeName("大修");
                break;
            default:
                vo.setMaintenanceTypeName("未知");
                break;
        }
        
        // 查询设备信息
        if (maintenance.getDeviceId() != null) {
            Device device = deviceService.getById(maintenance.getDeviceId());
            if (device != null) {
                vo.setDeviceName(device.getDeviceName());
                vo.setDeviceNo(device.getDeviceNo());
            }
        }
        
        return vo;
    }

    /**
     * 转换为运行VO
     */
    private DeviceOperationVO convertOperationToVO(DeviceOperation operation) {
        DeviceOperationVO vo = new DeviceOperationVO();
        // 复制基本属性
        vo.setId(operation.getId());
        vo.setOperationNo(operation.getOperationNo());
        vo.setDeviceId(operation.getDeviceId());
        vo.setOperationStatus(operation.getOperationStatus());
        vo.setStartTime(operation.getStartTime());
        vo.setEndTime(operation.getEndTime());
        vo.setRunHours(operation.getRunHours());
        vo.setOperator(operation.getOperator());
        vo.setOperationParams(operation.getOperationParams());
        vo.setOperationData(operation.getOperationData());
        vo.setAbnormalSituation(operation.getAbnormalSituation());
        vo.setHandlingMeasures(operation.getHandlingMeasures());
        vo.setEfficiency(operation.getEfficiency());
        vo.setEnergyConsumption(operation.getEnergyConsumption());
        vo.setOutput(operation.getOutput());
        vo.setRemark(operation.getRemark());
        vo.setTenantId(operation.getTenantId());
        vo.setCreateUser(operation.getCreateUser());
        vo.setCreateTime(operation.getCreateTime());
        vo.setUpdateTime(operation.getUpdateTime());
        
        // 设置运行状态名称
        switch (operation.getOperationStatus()) {
            case 1:
                vo.setOperationStatusName("开机");
                break;
            case 2:
                vo.setOperationStatusName("运行中");
                break;
            case 3:
                vo.setOperationStatusName("停机");
                break;
            case 4:
                vo.setOperationStatusName("故障");
                break;
            default:
                vo.setOperationStatusName("未知");
                break;
        }
        
        // 查询设备信息
        if (operation.getDeviceId() != null) {
            Device device = deviceService.getById(operation.getDeviceId());
            if (device != null) {
                vo.setDeviceName(device.getDeviceName());
                vo.setDeviceNo(device.getDeviceNo());
            }
        }
        
        return vo;
    }

    /**
     * 生成设备编号
     */
    private String generateDeviceNo() {
        return "DEV" + System.currentTimeMillis();
    }

    /**
     * 生成维护单号
     */
    private String generateMaintenanceNo() {
        return "MT" + System.currentTimeMillis();
    }

    /**
     * 生成运行记录编号
     */
    private String generateOperationNo() {
        return "OP" + System.currentTimeMillis();
    }
}
